package ObserverPattern;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zhaojie
 * @Date: Created in 17:08 2018/6/25
 * @Description: 被观察者
 */
public class Subject {
    private List<Observer> observers
            = new ArrayList<Observer>();
    private int state;

    public int getState() {
        return state;
    }

    //通过设置状态值 唤醒所有观察者
    public void setState(int state) {
        this.state = state;
        notifyAllObservers();
    }

    //订阅该被观察者 谁订阅就被添加到观察者列表
    public void attach(Observer observer) {
        observers.add(observer);
    }

    public void notifyAllObservers() {
        for (Observer observer : observers) {
            System.out.println(observer.getClass()+"观察");
            observer.update();
        }
    }
}
